package cn.huijielong.modules.app.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.gson.Gson;

import cn.huijielong.common.exception.VSException;
import cn.huijielong.common.props.PropsConfig;
import cn.huijielong.common.utils.Constant;
import cn.huijielong.common.utils.HttpClientRequest;
import cn.huijielong.common.utils.Query;
import cn.huijielong.modules.app.entity.UserEntity;
import cn.huijielong.modules.app.service.WechatService;
import cn.huijielong.modules.pub.dao.MerchantDao;
import cn.huijielong.modules.pub.dao.UserOpenidDao;
import cn.huijielong.modules.pub.entity.UserOpenidEntity;
import cn.huijielong.modules.sys.dao.SysUserRoleDao;
import cn.huijielong.modules.sys.entity.SysUserEntity;
import cn.huijielong.modules.sys.service.SysUserService;
import cn.huijielong.modules.sys.service.impl.SimpleServiceImpl;

@Service("wechatService")
public class WechatServiceImpl extends SimpleServiceImpl implements WechatService {
	@Autowired
    private PropsConfig propsConfig;
	@Autowired
	private MerchantDao merchantDao;
	@Autowired
	private UserOpenidDao userOpenidDao;
	@Autowired
	private SysUserRoleDao sysUserRoleDao;
	@Autowired
	private SysUserService sysUserService;
	
	private HttpClientRequest httpClient=HttpClientRequest.newClient();
	
	@Override
	public UserEntity getWxUserinfo(String code) {
		String appid=propsConfig.getWx().getAppId();
		String secret=propsConfig.getWx().getAppSecret();
		
		String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret="
				+ secret+ "&js_code=" + code + "&grant_type=authorization_code";
		logger.info(url);
		String reusult = httpClient.httpGet(url);
		Query q=new Gson().fromJson(reusult, Query.class);
		if(q.getString("openid").length()==0) {
			logger.error("微信授权失败，从微信返回结果为：{}",q.getString("errmsg"));
			throw new VSException("微信授权失败");
		}
		UserEntity user=new UserEntity();
		user.setOpenid(q.getString("openid"));
		return user;
	}
	@Transactional
	@Override
	public UserEntity getUserinfo(UserEntity user) {
		UserOpenidEntity userOpen=userOpenidDao.queryByOpenid(user.getOpenid());
		
		Long roleId=Constant.ROLE_QRTUAN;
		if(userOpen==null) {
			SysUserEntity sysUser=new SysUserEntity();
			sysUser.setPassword("123456");
			sysUser.setUsername(user.getUsername());
			sysUser.setNickName(user.getNickName());
			
			List<Long> roles=new ArrayList<>();
			if(roleId!=null) {
				roles.add(roleId);
			}
			
			sysUser.setRoleIdList(roles);
			sysUser.setCreateUserId(Long.valueOf(Constant.SUPER_ADMIN));
			sysUser.setStatus(1);
			sysUserService.save(sysUser);
			user.setUserId(sysUser.getUserId());
			
			UserOpenidEntity uoe=new UserOpenidEntity();
			uoe.setHeadImg(user.getHeadImg());
			uoe.setNickName(user.getNickName());
			uoe.setOpenid(user.getOpenid());
			uoe.setUserId(sysUser.getUserId());
			userOpenidDao.save(uoe);
		}else {
			user.setUserId(userOpen.getUserId());
			Long merchantId=merchantDao.querySelectedMerchantId(userOpen.getUserId());
			user.setMerchantId(merchantId);
			if(roleId!=null) {
				List<Long> roleList=sysUserRoleDao.queryRoleIdList(userOpen.getUserId());
				//角色不存在，添加
				if(roleList!=null && !roleList.contains(roleId)) {
					Map<String, Object> userRole = new HashMap<>();
					userRole.put("userId", userOpen.getUserId());
					userRole.put("roleIdList", Arrays.asList(roleId));
					sysUserRoleDao.save(userRole);
				}
			}
		}
		return user;
	}
}
